package com.googlecode.chigs.web.common;

import java.util.List;

import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.synyx.hades.domain.AbstractPersistable;

import com.googlecode.chigs.repository.GenericDomainService;
import com.inmethod.grid.IDataSource;
import com.inmethod.grid.IGridSortState;
import com.inmethod.grid.IGridSortState.ISortStateColumn;

/**
 * Generischer Dataprovider für die Inmethod Grids.
 * @author Ingo Renner
 * @author Henning Teek
 *
 * @param <T>
 */
public class GenericDataSource<T extends AbstractPersistable<Long>> implements IDataSource {
	@SpringBean
	private GenericDomainService genericDomainService;

	private final Class<T> type;

	@SuppressWarnings("unchecked")
	public GenericDataSource(T domainObject) {
		InjectorHolder.getInjector().inject(this);
		this.type = (Class<T>) domainObject.getClass();
	}

	@SuppressWarnings("unchecked")
	@Override
	public IModel<T> model(Object object) {
		return new DomainObjectModel<T>((T)object);
	}

	@Override
	public void query(IQuery query, IQueryResult result) {

		String sortProperty = null;
		boolean sortAsc = true;

		// is there any sorting
		if (query.getSortState().getColumns().size() > 0) {
			// get the most relevant column 
			ISortStateColumn state = query.getSortState().getColumns().get(0);

			// get the column sort properties
			sortProperty = state.getPropertyName();
			sortAsc = state.getDirection() == IGridSortState.Direction.ASC;
		}

		// determine the total count
		result.setTotalCount(genericDomainService.getCount(type));

		// get the actual items
		List<T> resultList = genericDomainService.loadAll(type, query.getFrom(), query.getCount(), sortProperty, sortAsc);
		result.setItems(resultList.iterator());
	}

	@Override
	public void detach() {
	}
}
